package com.itheima.aspects;
import java.time.LocalDateTime;
import java.util.Arrays;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.itheima.domain.pojo.OperateLog;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author:篍
 * @Date: 2025/07/18 14:18
 * @Description:记录增删改日志
 */
@Slf4j
@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    OperateLogMapper operateLogMapper;

    /**
     * 记录操作日志
     * @param代理对象
     * @return目标方法返回值
     * @throws Throwable
     */
    @Around("@annotation(com.itheima.anno.LogOperation)")
    public Object addOperateLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        OperateLog operateLog=new OperateLog();
        //获取操作员工id
        Integer id= ThreadLocalUtils.getId();
        operateLog.setOperateEmpId(id);
        //操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        String name = proceedingJoinPoint.getClass().getName();
        log.warn("name={}",name);
        String targetName = proceedingJoinPoint.getTarget().getClass().getName();
        operateLog.setClassName(targetName);
        String methodName = proceedingJoinPoint.getSignature().getName();
        operateLog.setMethodName(methodName);
        Object[] args = proceedingJoinPoint.getArgs();
        String methodParams="";
        if(ArrayUtil.isNotEmpty(args)){
            methodParams= Arrays.toString(args);
        }
        //方法参数
        operateLog.setMethodParams(methodParams);
        long begin = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();
        //返回值
        operateLog.setReturnValue(JSONUtil.toJsonStr(result));
        //耗时
        operateLog.setCostTime(end-begin);
        operateLogMapper.addOperateLog(operateLog);
        return result;

    }
}
